import React, {Component} from "react";
import { connect } from 'react-redux';
import { Select, Form } from 'antd';
import emitter from '@/events';
import * as types from "@/store/actionTypes";
import { lesson_classList } from '@/api/userCenter';

const { Option } = Select;

class ClassSelect extends Component{

    render() {
        const { list = [] } = this.props;
        return (
            <Form.Item name={this.props.name}>
                <Select placeholder="班级名称" allowClear>
                    {
                        list.map(item => <Option value={item.classCode} key={item.id}>{item.className}</Option>)
                    }
                </Select>
            </Form.Item>
        )
    }

    componentDidMount() {
        emitter.on('schoolSelect', (res) => {
            res && this.props.getClass(res);
            this.props.setValue({'classCodes': undefined})
        })
    }

    componentWillUnmount() {
        this.props.clearClass();
        emitter.removeAllListeners(["schoolSelect"])
    }
}

const mapStateToProps = (state) => {
    return {
        list: state.school_class.list
    }
};
const mapDispatchToProps = (dispatch) => {
    return {
        getClass: (id) => {
            lesson_classList(id).then(res => {
                if(res.success){
                    const { data } = res;
                    dispatch({
                        type: types.SCHOOL_CLASS,
                        list: data
                    })
                }
            })
        },
        clearClass: () => {
            dispatch({
                type: types.SCHOOL_CLASS,
                list: []
            })
        }
    }
};

export default connect(mapStateToProps, mapDispatchToProps)(ClassSelect)
